/**
 * 认证工具函数库 - 函数式实现
 * 提供与用户认证相关的各种工具函数
 */

// 存储键名常量
const AUTH_TOKEN_KEY = 'auth_token';
const USER_INFO_KEY = 'user_info';

// Token 管理函数
export const getToken = () => {
    return localStorage.getItem(AUTH_TOKEN_KEY) || sessionStorage.getItem(AUTH_TOKEN_KEY);
};

export const setToken = (tokenValue, rememberMe = false) => {
    if (rememberMe) {
        localStorage.setItem(AUTH_TOKEN_KEY, tokenValue);
    } else {
        sessionStorage.setItem(AUTH_TOKEN_KEY, tokenValue);
    }
};

export const removeToken = () => {
    localStorage.removeItem(AUTH_TOKEN_KEY);
    sessionStorage.removeItem(AUTH_TOKEN_KEY);
};

export const hasToken = () => {
    return !!getToken();
};

// 用户信息管理函数
export const getUserInfo = () => {
    const userData = localStorage.getItem(USER_INFO_KEY) || sessionStorage.getItem(USER_INFO_KEY);
    return userData ? JSON.parse(userData) : null;
};

export const setUserInfo = (userInfo, rememberMe = false) => {
    const userData = JSON.stringify(userInfo);
    if (rememberMe) {
        localStorage.setItem(USER_INFO_KEY, userData);
    } else {
        sessionStorage.setItem(USER_INFO_KEY, userData);
    }
};

export const removeUserInfo = () => {
    localStorage.removeItem(USER_INFO_KEY);
    sessionStorage.removeItem(USER_INFO_KEY);
};

// 权限验证函数
export const hasPermission = (requiredPermissions) => {
    const userInfo = getUserInfo();
    if (!userInfo || !userInfo.permissions) return false;

    const userPermissions = userInfo.permissions;

    if (Array.isArray(requiredPermissions)) {
        return requiredPermissions.every(perm => userPermissions.includes(perm));
    }

    return userPermissions.includes(requiredPermissions);
};

// 认证状态检查
export const isAuthenticated = () => {
    return hasToken();
};

// 登出函数
export const logout = () => {
    removeToken();
    removeUserInfo();
};

// 重定向到登录页
export const redirectToLogin = () => {
    logout();
    window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname + window.location.search);
};

// 令牌刷新函数
export const refreshToken = async () => {
    try {
        const response = await fetch('/api/auth/refresh', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            const data = await response.json();
            setToken(data.token);
            return true;
        }

        return false;
    } catch (error) {
        console.error('令牌刷新失败:', error);
        return false;
    }
};

// 默认导出所有函数
export default {
    getToken,
    setToken,
    removeToken,
    hasToken,
    getUserInfo,
    setUserInfo,
    removeUserInfo,
    hasPermission,
    isAuthenticated,
    logout,
    redirectToLogin,
    refreshToken
};